﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityStandardAssets._2D;

[RequireComponent(typeof(MovingPlatform))]
public class TickablePlatform : MonoBehaviour
{
    public float tickDuration = 0.25f;


    private float nextTickTime = Single.NaN;


    void Start()
    {

    }

    public virtual void OnTick(PlatformerCharacter2D character)
    {
    }

    void Update()
    {
        var character = GetComponent<MovingPlatform>().connectedBodies
            .Select(b => b.GetComponent<PlatformerCharacter2D>())
            .Where(c => (c != null)).FirstOrDefault();

        if (character != null)
        {
            if (float.IsNaN(nextTickTime))
            {
                OnTick(character);
                nextTickTime = Time.time + tickDuration;
            }
            else if (Time.time >= nextTickTime)
            {
                OnTick(character);
                nextTickTime += tickDuration; 
            }
        }
        else nextTickTime = Single.NaN;
    }
}
